package com.linck.im.client.handler;

import com.linck.im.model.proto.ProtoMsg;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 心跳处理 指定时间未发生写时间，向服务器发送心跳包
 *
 * @author: linck
 * @create: 2021-01-28
 */
public class ClientHeartBeatHandler extends SimpleChannelInboundHandler<ProtoMsg.HeartBeat> {

    private static final Logger log = LoggerFactory.getLogger(ClientHeartBeatHandler.class);

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ProtoMsg.HeartBeat heartBeat) throws Exception {
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            // 超过指定时间，未发生写入操作，发送心跳包
            if (IdleState.WRITER_IDLE.equals(event.state())) {
                ctx.writeAndFlush(ProtoMsg.HeartBeat.newBuilder().build());
            }
        }
    }
}
